package com.jsle.financial.action;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.jsle.financial.domain.Node;
import com.jsle.financial.domain.User;
import com.jsle.financial.domain.Workflow;
import com.jsle.financial.service.UserService;
import com.jsle.financial.service.WorkflowService;
import com.jsle.financial.util.AJAXUtil;
import com.jsle.financial.util.Constants;
import com.jsle.financial.util.WorkflowUtil;
import com.jsle.financial.vo.Result;

@Controller
@RequestMapping("/workflow")
public class AmountWorkflowController {
	private Log log = LogFactory.getLog(AmountWorkflowController.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Resource
	private WorkflowService workflowService;
	@Resource
	private UserService userService;
	@RequestMapping(value = "/createApply.do",method=RequestMethod.POST)
	public void createApply(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String workflowName = WebUtils.findParameterValue(request, "workflowName");
		String type = WebUtils.findParameterValue(request, "workflowType");
		int workflowType = Integer.valueOf(type);
		String formCode = WebUtils.findParameterValue(request, "formCode");
		User user = (User)request.getSession().getAttribute("user");
		BigDecimal amount = null;
		String amountStr = WebUtils.findParameterValue(request, "amount");
		if((amountStr!=null)&&(!"".equals(amountStr))){
			amount = BigDecimal.valueOf(Double.valueOf(amountStr));
		}
		
		String workflowDescription = WebUtils.findParameterValue(request, "workflowDescription");
		//Integer applicantId = Integer.valueOf(WebUtils.findParameterValue(request, "applicantId"));
		String assessorIds = WebUtils.findParameterValue(request, "assessorIds");
		String companyCode = user.getCompanyCode();//Integer.valueOf(WebUtils.findParameterValue(request, "companyCode"));//可以从上下文中取到
		String nodeName = WebUtils.findParameterValue(request, "nodeName");
		
		System.out.println("workflowName"+workflowName+" amount:"+amount+" workflowDescription:"+workflowDescription+" applicantId:"+user.getId()+" assessorIds:"+assessorIds+" companyCode:"+companyCode+" nodeName:"+nodeName);
		//1、创建流程信息
		String workflowCode = Constants.getUUID();
		workflowService.saveAmountWorkflow(new Workflow(formCode,workflowName,Constants.Workflow.FC_WORKFLOW_STATUS_APPLIED,workflowType,companyCode, Constants.Workflow.FC_WORKFLOW_NODE_1,assessorIds.split(",").length,0,workflowCode,user.getId(),user.getcNName(),amount,workflowDescription));
		Result result = workflowService.queryWorkflowByCode(workflowCode);
		Workflow workflow = null;
		if((result!=null)&&(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE)){
			workflow = (Workflow)result.getResultValue();
			//2、创建申请节点信息
			Node node = new Node(nodeName,amount,user.getId(),null,null,workflowDescription,workflowCode,Constants.Workflow.FC_WORKFLOW_NODE_1);
			workflowService.saveAmountNode(node);
			
			//3、创建审批节点信息
			String[] assessorArray = assessorIds.split(",");
			for (int i = 0; i < assessorArray.length; i++) {
				Node nextNode = new Node(nodeName,null,null,Integer.valueOf(assessorArray[i]),null,"",workflowCode,Constants.Workflow.FC_WORKFLOW_NODE_2);
				workflowService.saveAmountNode(nextNode);
			}
		}
		
		System.out.println("####"+workflowName);
		String json = "{\"success\":\"true\"}";
		AJAXUtil.writerJson(response,json);
	}
	@RequestMapping(value = "/queryAssessors",produces = "application/json")
	@ResponseBody
	public void queryAssessors(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String userId = WebUtils.findParameterValue(request, "userId");
		String companeyCode = WebUtils.findParameterValue(request, "companeyCode");
		System.out.println("userId:::"+userId+"  companeyCode:::"+companeyCode);
		User user = (User)request.getSession().getAttribute("user");
		System.out.println("####CNName:::"+user.getcNName());
		Result result = userService.queryAssessors(user);
		List<User> users = null;
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			users = (List<User>)result.getResultValue();
		}
		StringBuffer sb = new StringBuffer();
		if(users!=null){
			for (User userx : users) {
				sb.append("{").append("\"assessorId\":").append("\"").append(userx.getId()).append("\"").append(",");
				sb.append("\"assessorName\":").append("\"").append(userx.getcNName()).append("\"").append("},");
			}
		}
		if(sb!=null){
			if (sb.toString().endsWith(",")) {
				sb.deleteCharAt(sb.length() - 1);
			}
		}
		
		String json = "{success:true, data:[" + sb.toString() + "]}";
		AJAXUtil.writerJson(response,json);
	}
	@RequestMapping(value = "/createAssessor",produces = "application/json")
	@ResponseBody
	public void createAssessor(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String workflowCode = WebUtils.findParameterValue(request, "workflowCode");
		String approveResult = WebUtils.findParameterValue(request, "approveResult");
		User user = (User)request.getSession().getAttribute("user");
		Integer assessorId = user.getId();//Integer.valueOf(WebUtils.findParameterValue(request, "assessorId"));//从上下文中得到
		String nodeName = WebUtils.findParameterValue(request, "nodeName");

		//1、获取流程信息
		Result result = workflowService.queryWorkflowByCode(workflowCode);
		Workflow workflow = null;
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			workflow = (Workflow)result.getResultValue();
		}

		//2、执行审批节点某人审批操作
		Node node = new Node(nodeName,null,null,assessorId,null,approveResult,workflow.getWorkflowCode(),Constants.Workflow.FC_WORKFLOW_NODE_2);
		Result resultNode = workflowService.updateNode(node);
		boolean updateNodeResult = false;
		if(resultNode.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			updateNodeResult = (Boolean)resultNode.getResultValue();
		}

		//3、更新流程信息
		if((workflow.getNodeCompletedOperators() + 1)==workflow.getNodeOperators()){
			workflow.setNodeCode(Constants.Workflow.FC_WORKFLOW_NODE_3);
			workflow.setNodeCompletedOperators(0);
		}else{
			workflow.setNodeCode(Constants.Workflow.FC_WORKFLOW_NODE_2);
			workflow.setNodeCompletedOperators(workflow.getNodeCompletedOperators() + 1);
		}
		workflowService.updateWorkflow(workflow);
		//4、获取更新后的流程信息
		Result updateWfResult = workflowService.queryWorkflowByCode(workflowCode);
		Workflow updatedWorkflow = null;
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			updatedWorkflow = (Workflow)updateWfResult.getResultValue();
		}
		Result resultApprove = userService.queryApproves(user);
		List<User> approveUsers = null;
		if(resultApprove.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			 approveUsers = (List<User>)resultApprove.getResultValue();
		}
		if((workflow.getNodeCompletedOperators() + 1)==workflow.getNodeOperators()){
			Integer auditor = null;//从用户组拿董事长id
			//4、创建拍板节点信息
			Node nodeAudit = new Node("董事长审批节点",null,null,null,((User)approveUsers.get(0)).getId(),"",workflowCode,Constants.Workflow.FC_WORKFLOW_NODE_3);
			workflowService.saveAmountNode(nodeAudit);
		}
		String json = "{\"success\":\"ture\"}";
		AJAXUtil.writerJson(response,json);
	}
	@RequestMapping(value = "/createAuditor",produces = "application/json")
	@ResponseBody
	public void createAuditor(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String workflowCode = WebUtils.findParameterValue(request, "workflowCode");
		String approveResult = WebUtils.findParameterValue(request, "approveResult");
		//Integer auditorId = Integer.valueOf(WebUtils.findParameterValue(request, "auditorId"));
		User user = (User)request.getSession().getAttribute("user");
		String nodeName = WebUtils.findParameterValue(request, "nodeName");
		//1、获取流程信息
		Result result = workflowService.queryWorkflowByCode(workflowCode);
		Workflow workflow = null;
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			workflow = (Workflow)result.getResultValue();
		}
		//2、执行拍板节点操作
		Node node = new Node(nodeName,null,null,null,user.getId(),approveResult,workflow.getWorkflowCode(),Constants.Workflow.FC_WORKFLOW_NODE_3);
		Result resultNode = workflowService.updateNode(node);
		if(resultNode.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			//3、更新流程信息
			workflow.setNodeCode(Constants.Workflow.FC_WORKFLOW_NODE_3);
			workflow.setNodeCompletedOperators(1);
			workflow.setWorkflowCode(workflow.getWorkflowCode());
			workflowService.updateWorkflow(workflow);
		}
		String json = "{\"success\":\"ture\"}";
		AJAXUtil.writerJson(response,json);
	}
	
	@RequestMapping(value = "/queryWorkflowByUser",produces = "application/json")
	@ResponseBody
	public void queryWorkflowByUser(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		Integer userId = Integer.valueOf(WebUtils.findParameterValue(request, "userId"));
		Result result = workflowService.queryWorkflowByUser(new User(userId));
		List<Workflow> workflows = new ArrayList<Workflow>();
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			workflows = (List<Workflow>)result.getResultValue();
		}
		StringBuffer sb = new StringBuffer();
		for (Workflow workflow : workflows) {
			sb.append("{").append("\"workflowName\":").append("\"").append(workflow.getWorkflowName()).append("\"").append(",");
			sb.append("\"applyUserName\":").append("\"").append(workflow.getApplyUserName()).append("\"").append(",");
			sb.append("\"workflowCode\":").append("\"").append(workflow.getWorkflowCode()).append("\"").append(",");
			sb.append("\"createTime\":").append("\"").append(sdf.format(workflow.getCreateTime())).append("\"").append("},");
		}
		if(sb!=null){
			if (sb.toString().endsWith(",")) {
				sb.deleteCharAt(sb.length() - 1);
			}
		}
		
		String json = "{success:true, data:[" + sb.toString() + "]}";
		AJAXUtil.writerJson(response,json);
	}
	
	@RequestMapping(value = "/queryWorkflowBySelf",produces = "application/json")
	@ResponseBody
	public void queryWorkflowBySelf(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		Integer workflowType = Integer.valueOf(WebUtils.findParameterValue(request, "workflowType"));
		User user = (User)request.getSession().getAttribute("user");
		Workflow wf = new Workflow();
		wf.setApplyUserId(user.getId());
		wf.setWorkflowType(workflowType);
		Result result = workflowService.queryWorkflowBySelf(wf);
		List<Workflow> workflows = new ArrayList<Workflow>();
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			workflows = (List<Workflow>)result.getResultValue();
		}
		StringBuffer sb = new StringBuffer();
		for (Workflow workflow : workflows) {
			sb.append("{").append("\"workflowName\":").append("\"").append(workflow.getWorkflowName()).append("\"").append(",");
			sb.append("\"applyUserName\":").append("\"").append(workflow.getApplyUserName()).append("\"").append(",");
			sb.append("\"workflowCode\":").append("\"").append(workflow.getWorkflowCode()).append("\"").append(",");
			sb.append("\"createTime\":").append("\"").append(sdf.format(workflow.getCreateTime())).append("\"").append("},");
		}
		if(sb!=null){
			if (sb.toString().endsWith(",")) {
				sb.deleteCharAt(sb.length() - 1);
			}
		}
		
		String json = "{success:true, data:[" + sb.toString() + "]}";
		AJAXUtil.writerJson(response,json);
	}
//	public void query(HttpServletRequest request,HttpServletResponse response){
//		AJAXUtil.setCharacterEncoding(request,response);
//		String workflowCode = WebUtils.findParameterValue(request, "workflowCode");
//		Result result = workflowService.queryWorkflowAndNodes(new Workflow(workflowCode));
//		List<WorkflowAndNode> workflowAndNodes = new ArrayList<WorkflowAndNode>();
//		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
//			workflowAndNodes = (List<WorkflowAndNode>)result.getResultValue();
//		}
//		StringBuffer sb = new StringBuffer();
//		for (WorkflowAndNode workflowAndNode : workflowAndNodes) {
//			
//		}
//		for (Workflow workflow : workflows) {
//			sb.append("{").append("\"workflowName\":").append("\"").append(workflow.getWorkflowName()).append("\"").append(",");
//			sb.append("\"applyUserName\":").append("\"").append(workflow.getApplyUserName()).append("\"").append(",");
//			sb.append("\"workflowCode\":").append("\"").append(workflow.getWorkflowCode()).append("\"").append(",");
//			sb.append("\"createTime\":").append("\"").append(sdf.format(workflow.getCreateTime())).append("\"").append("},");
//		}
//		if(sb!=null){
//			if (sb.toString().endsWith(",")) {
//				sb.deleteCharAt(sb.length() - 1);
//			}
//		}
//		
//		String json = "{success:true, data:[" + sb.toString() + "]}";
//		AJAXUtil.writerJson(response,json);
//	}
	@RequestMapping(value = "/queryWorkflowAndNodes",produces = "application/json")
	@ResponseBody
	public void queryWorkflowAndNodes(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String workflowCode = WebUtils.findParameterValue(request, "workflowCode");
		Result result = workflowService.queryWorkflowByCode(workflowCode);
		Workflow workflow = null;
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			workflow = (Workflow)result.getResultValue();
		}
		StringBuffer workflowsb = new StringBuffer();
		workflowsb.append("\"currentUserId\":").append("\"").append("1").append("\",");
		workflowsb.append("\"formCode\":").append("\"").append(workflow.getFormCode()).append("\",");
		workflowsb.append("\"workflowName\":").append("\"").append(workflow.getWorkflowName()).append("\",");
		workflowsb.append("\"amount\":").append("\"").append(workflow.getAmount()).append("\",");
		workflowsb.append("\"workflowType\":").append("\"").append(workflow.getWorkflowType()).append("\",");
		workflowsb.append("\"workflowDescription\":").append("\"").append(workflow.getWorkflowDescription()).append("\",");
		workflowsb.append("\"applyUserName\":").append("\"").append(workflow.getApplyUserName()).append("\",");
		workflowsb.append("\"createTime\":").append("\"").append(sdf.format(workflow.getCreateTime())).append("\",");
		workflowsb.append("data:[");
		Result nodeResult = workflowService.queryNodes(new Workflow(workflowCode));
		List<Node> nodes = new ArrayList<Node>();
		if(nodeResult.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			nodes = (List<Node>)nodeResult.getResultValue();
		}
		User assessorUser = null;
		User approveUser = null;
		
		for (Node node : nodes) {
			workflowsb.append("{");
			workflowsb.append("\"assessorId\":").append("\"").append(node.getAssessorId()==null?"":node.getAssessorId()).append("\",");
			if(node.getAssessorId()!=null){
				Result resultassessor = userService.queryUserById(node.getAssessorId());
				if(resultassessor.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
					assessorUser = (User)resultassessor.getResultValue();
					workflowsb.append("\"assessorName\":").append("\"").append(assessorUser.getcNName()).append("\",");
				}
			}else{
				workflowsb.append("\"assessorName\":").append("\"\"").append(",");
			}
			if(node.getApproveId()!=null){
				Result resultapprove = userService.queryUserById(node.getApproveId());
				if(resultapprove.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
					approveUser = (User)resultapprove.getResultValue();
					workflowsb.append("\"approveName\":").append("\"").append(approveUser.getcNName()).append("\",");
				}
			}else{
				workflowsb.append("\"approveName\":").append("\"\"").append(",");
			}
			workflowsb.append("\"approveId\":").append("\"").append(node.getApproveId()==null?"":node.getApproveId()).append("\",");
			
			workflowsb.append("\"nodeCode\":").append(node.getNodeCode()).append(",");
			workflowsb.append("\"approveResult\":").append("\"").append(node.getApproveResult()).append("\",");
			workflowsb.append("\"createTime\":").append("\"").append(sdf.format(node.getCreateTime())).append("\"},");
		}
		if(workflowsb!=null){
			if (workflowsb.toString().endsWith(",")) {
				workflowsb.deleteCharAt(workflowsb.length() - 1);
			}
		}
		workflowsb.append("]");
		String json = "{success:true, "+workflowsb.toString()+"}";
		System.out.println("json###"+json);
		AJAXUtil.writerJson(response,json);
	}
	@RequestMapping(value = "/createFormCode",produces = "application/json")
	@ResponseBody
	public void createFormCode(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String prefixStr = WebUtils.findParameterValue(request, "prefixStr");
		String json = "";
		String formCode = WorkflowUtil.FormCode(prefixStr);
		json = "{\"success\":\"true\", \"formCode\":\""+formCode+"\"}";
		System.out.println("json::::::::::::"+json);
		AJAXUtil.writerJson(response,json);
	}
	@RequestMapping(value = "/queryWorkflowByWorkflow",produces = "application/json")
	@ResponseBody
	public void queryWorkflowByWorkflow(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		User user = (User)request.getSession().getAttribute("user");
		String applyUserName = WebUtils.findParameterValue(request, "applyUserName");
		String formCode = WebUtils.findParameterValue(request, "formCode");
		Workflow wf = new Workflow();
		wf.setApplyUserName(applyUserName);
		wf.setFormCode(formCode);
		wf.setCompanyCode(user.getCompanyCode());
		String json = "";
		List<Workflow> workflows = new ArrayList<Workflow>();
		Result result = workflowService.queryWorkflowByWorkflow(wf);
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			workflows = (List<Workflow>)result.getResultValue();
		}
		StringBuffer sb = new StringBuffer();
		for (Workflow workflow : workflows) {
			sb.append("{").append("\"workflowName\":").append("\"").append(workflow.getWorkflowName()).append("\"").append(",");
			sb.append("\"applyUserName\":").append("\"").append(workflow.getApplyUserName()).append("\"").append(",");
			sb.append("\"formCode\":").append("\"").append(workflow.getFormCode()).append("\"").append(",");
			sb.append("\"workflowCode\":").append("\"").append(workflow.getWorkflowCode()).append("\"").append(",");
			sb.append("\"createTime\":").append("\"").append(sdf.format(workflow.getCreateTime())).append("\"").append("},");
		}
		if(sb!=null){
			if (sb.toString().endsWith(",")) {
				sb.deleteCharAt(sb.length() - 1);
			}
		}
		
		json = "{success:true, data:[" + sb.toString() + "]}";
		AJAXUtil.writerJson(response,json);
	}
}
